import 'dart:developer';

import 'package:dio/dio.dart';
import 'package:edu/networks/business/models/business_response.dart';
import 'package:edu/utils/account_info.dart';
import 'package:edu/utils/data_fetcher.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class EduPageLogic extends ChangeNotifier {
  final List<CourseOrder> purchasedCourses = [];

  bool loading = false;
  bool error = false;

  bool get isContentEmpty => purchasedCourses.isEmpty;

  late final _cancelToken = CancelToken();

  void init() {
    AccountInfo.shared.userBriefNotifier.addListener(_userBriefListener);

    Future.delayed(Duration.zero, loadPurchasedCourses);
  }

  @override
  void dispose() {
    AccountInfo.shared.userBriefNotifier.removeListener(_userBriefListener);
    _cancelToken.cancel();
    super.dispose();
  }

  // 监听用户信息
  void _userBriefListener() {
    loadPurchasedCourses();
  }

  // 加载已购买的课程
  void loadPurchasedCourses() {
    // 获取已购买的课程,防止课程重复
    final purchasedCourseIdList = AccountInfo.shared.purchasedCourses;
    final fetchedCourseIdList = purchasedCourses.map((e) => e.id).toList();
    final difference = purchasedCourseIdList
        .where((element) => !fetchedCourseIdList.contains(element))
        .toList();

    // 存在未加载的课程
    if (difference.isNotEmpty && !loading) {
      _loadPurchasedCourses(difference);
    }
  }

  // 加载已购买的课程
  void _loadPurchasedCourses(List<int> courseIds) async {
    try {
      EasyLoading.show(
        indicator: const CircularProgressIndicator(),
        maskType: EasyLoadingMaskType.black,
        dismissOnTap: false,
      );
      loading = true;
      error = false;
      notifyListeners();

      final response = await DataFetcher.shared.businessApi.getCourseOrders(
        courseIds: courseIds,
        cancelToken: _cancelToken,
      );
      loading = false;
      EasyLoading.dismiss();

      if (response.code == 0 && response.orders != null) {
        final fetchedCourseIdList = purchasedCourses.map((e) => e.id).toList();
        final newOrders = response.orders!
            .where((element) => !fetchedCourseIdList.contains(element.id))
            .toList();
        purchasedCourses.addAll(newOrders);
      } else {
        error = true;
        EasyLoading.showError(response.message ?? '加载失败');
      }
      notifyListeners();
    } on DioException catch (e) {
      EasyLoading.dismiss();
      loading = false;
      if (e.type == DioExceptionType.cancel) {
        return;
      }
      error = true;
      notifyListeners();
      EasyLoading.showError(e.toString());
    } catch (e) {
      log('Error: $e');
    }
  }
}
